import axios from 'axios';
import CustomError from '@/common/error';
import router from '@/router';
import { getLocal } from './utils';

// ? 创建一个axios的实例
const api = axios.create({
  // ? 过期时间
  timeout: 5000,
});

// ? 拦截器
// ? 说白了还是钩子函数
// ? 发请求之前，对请求做一些操作
api.interceptors.request.use(
  (request) => {
    const user = getLocal('user');
    if (!user) {
      const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7Il9pZCI6IjYzNmIxNjNiN2M0YjI5NmM1YmNhN2U0MiIsInVzZXJuYW1lIjoiaGhyMTIzIiwicGFzc3dvcmQiOiIkMmIkMTAkV3BqQVFzUVh0WVVmc3QvSC44RVdtT01CLlVZczZUdlpxVG44QldVTk1iRk9BM0pjNndxdU8iLCJuaWNrbmFtZSI6IiIsImNyZWF0ZWRBdCI6IjIwMjItMTEtMDlUMDI6NTM6NDcuMjYzWiIsInVwZGF0ZWRBdCI6IjIwMjItMTEtMDlUMDI6NTM6NDcuMjY1WiIsIl9fdiI6MH0sImlhdCI6MTY2ODgyMzI1NSwiZXhwIjoxNjY5MDgyNDU1fQ.57xlCQpZp07MZuF2OXSWMd0fThuCdlftGtuQbivL4m8';
      // eslint-disable-next-line no-param-reassign
      request.headers.authorization = `${token}`;
    }
    return request;
  },
  (error) => Promise.reject(error),
);

// ? 获取响应后，对响应做一些操作
api.interceptors.response.use(
  (response) => response.data,
  (error) => {
    const customError = new CustomError(error);
    // return Promise.reject(customError);
    if (customError.code === 'auth-failed') {
      // eslint-disable-next-line no-alert
      alert('请重新登录');
      router.push('/login');
    }
  },
);

export default api;
